﻿using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;

namespace xiapibuy_collect.utils
{
    public class HttpClientKit
    {

        public static async Task<String> ReadWithAngleSharpAsync(String url)
        {

            var htmlSourceCode = await ResponseWithErrorsAsync(url);

            

            /* var parser = new HtmlParser(); 
              var document = await  parser.ParseDocumentAsync(htmlSourceCode);*/
            return htmlSourceCode;

        }

        public static async Task<String> ResponseWithErrorsAsync(String url)
        {
            try
            {
                var httpclientHandler = new HttpClientHandler();
                httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
                var client = new HttpClient(httpclientHandler);
                client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36");
                client.DefaultRequestHeaders.Add("x-api-source", "pc");
                client.DefaultRequestHeaders.Add("x-requested-with", "XMLHttpRequest");
                client.DefaultRequestHeaders.Add("access-control-allow-credentials", "true");
                client.DefaultRequestHeaders.Add("access-control-allow-headers", "true");
                client.DefaultRequestHeaders.Add("If-None-Match-", "55b03-b82f52a1d24e95c54bff64720187e75e");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var host = "https://xiapi.xiapibuy.com/api/v2/";
                Console.WriteLine("爬取网站url>>"+ host + url);
                var responseBody = await client.GetAsync( host+url);
                if (responseBody.IsSuccessStatusCode)
                {
                    string str = await responseBody.Content.ReadAsStringAsync();

                    return str;
                }
                else
                {
                    return null;
                }
               

               
            }
            catch (HttpRequestException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Message :{0} ", e.Message);
                return null;
            }
        }
    }
}
